package com.oauth.service.generic;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.oauth.service.generic.beans.OAuthServiceBean;
import com.oauth.service.generic.dao.OAuthDAO;
import com.oauth.service.generic.exception.OAuthServiceException;

@Service
public class OAuthServiceImpl implements OAuthService {

	@Autowired
	private OAuthDAO mOAuthDAO;

	@Override
	public void deleteToken(Long memberId, Long applicationId) throws OAuthServiceException {
		if (null == memberId || applicationId == null) {
			throw new OAuthServiceException("Parameters are null:MemberId" + memberId
					+ "ApplicationId=" + applicationId);
		}
		mOAuthDAO.deleteToken(memberId, applicationId);
	}

	@Override
	public OAuthServiceBean persistToken(OAuthServiceBean serviceBean) throws OAuthServiceException {
		if (serviceBean == null || serviceBean.getMemberId() == null
				|| serviceBean.getApplicationId() == null
				|| !StringUtils.hasText(serviceBean.getAccessToken())
				|| !StringUtils.hasText(serviceBean.getAccessTokenSecret())) {
			throw new OAuthServiceException("OAuthServiceBean Parameters are null" + serviceBean);
		}
		return mOAuthDAO.persistToken(serviceBean);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.oauth.service.generic.OAuthService#getToken(java.lang.Long,
	 * java.lang.Long)
	 */
	@Override
	public OAuthServiceBean getToken(Long memberId, Long applicationId)
			throws OAuthServiceException {
		if (memberId == null || applicationId == null) {
			throw new OAuthServiceException("Parameters are null:MemberId" + memberId
					+ "ApplicationId=" + applicationId);
		}
		return mOAuthDAO.getToken(memberId, applicationId);
	}

	@Override
	public List<OAuthServiceBean> getAllTokens(Long memberId) throws OAuthServiceException {
		if (memberId == null) {
			throw new OAuthServiceException("Parameters are null:MemberId" + memberId);
		}
		return mOAuthDAO.getAllTokens(memberId);
	}

	@Override
	public Set<Long> getApplicationsByMember(Long memberId) throws OAuthServiceException {
		List<OAuthServiceBean> allTokens = getAllTokens(memberId);
		Set<Long> applicationIdSet = new HashSet<Long>();
		if (allTokens != null) {
			for (OAuthServiceBean bean : allTokens) {
				applicationIdSet.add(bean.getApplicationId());
			}
		}
		return applicationIdSet;
	}

	/**
	 * @param pOAuthDAO
	 *            the oAuthDAO to set
	 */
	public void setoauthDAO(OAuthDAO pOAuthDAO) {
		mOAuthDAO = pOAuthDAO;
	}

}